<template>
  <div class="app-container">
    <el-card>
      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="search-form">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入部门名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 240px">
            <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <el-row :gutter="10" class="mb-3">
        <el-col :span="1.5">
          <el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="deptList"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="name" label="部门名称" :show-overflow-tooltip="true" />
        <el-table-column prop="sort" label="排序" width="80" align="center" />
        <el-table-column prop="leader" label="负责人" width="120" :show-overflow-tooltip="true" />
        <el-table-column prop="phone" label="联系电话" width="120" :show-overflow-tooltip="true" />
        <el-table-column prop="email" label="邮箱" width="180" :show-overflow-tooltip="true" />
        <el-table-column prop="status" label="状态" align="center" width="100">
          <template #default="scope">
            <dict-tag dict-type="sys_normal_disable" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" width="160">
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.createdAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="primary" link :icon="Plus" @click="handleAdd(scope.row)">新增</el-button>
            <el-button type="primary" link :icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="danger" link :icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="deptFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="上级部门">
          <el-tree-select
            v-model="form.parentId"
            :data="deptOptions"
            :props="{ label: 'name', children: 'children', value: 'id' }"
            value-key="id"
            placeholder="请选择上级部门"
            check-strictly
            clearable
          />
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="负责人" prop="leader">
          <el-input v-model="form.leader" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" controls-position="right" />
        </el-form-item>
        <el-form-item label="部门状态" prop="status">
          <dict-radio
            v-model="form.status"
            dict-type="sys_normal_disable"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="dialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { 
  getDeptList, 
  getDeptDetail,
  getDeptTree, 
  createDept, 
  updateDept, 
  deleteDept, 
  updateDeptStatus 
} from '@/api/dept'
import { validPhone, validEmail } from '@/utils/validate'
import useDict from '@/hooks/useDict'

// 状态数据字典
const statusOptions = [
  { value: 1, label: '正常' },
  { value: 0, label: '停用' }
]

// 查询参数
const queryParams = reactive({
  name: '',
  status: null
})

// 表格数据
const deptList = ref([])
const deptOptions = ref([])
const loading = ref(false)
const queryFormRef = ref(null)
const deptFormRef = ref(null)

// 表单参数
const form = reactive({
  id: null,
  parentId: null,
  name: '',
  leader: '',
  phone: '',
  email: '',
  sort: 0,
  status: 1
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '部门名称不能为空', trigger: 'blur' }
  ],
  phone: [
    { validator: validatePhone, trigger: 'blur' }
  ],
  email: [
    { validator: validateEmail, trigger: 'blur' }
  ]
}

// 部门表单对话框
const dialog = reactive({
  title: '',
  visible: false
})

// 字典数据
const { dicts } = useDict('sys_normal_disable')

// 格式化日期时间
const formatDateTime = (value) => {
  if (!value) return ''
  return new Date(value).toLocaleString()
}

// 电话号码验证
function validatePhone(rule, value, callback) {
  if (value && !validPhone(value)) {
    callback(new Error('请输入正确的电话号码'))
  } else {
    callback()
  }
}

// 邮箱验证
function validateEmail(rule, value, callback) {
  if (value && !validEmail(value)) {
    callback(new Error('请输入正确的邮箱地址'))
  } else {
    callback()
  }
}

// 获取部门列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getDeptList(queryParams)
    deptList.value = res.data
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败')
  } finally {
    loading.value = false
  }
}

// 获取部门树选项
const getDeptOptions = async () => {
  try {
    const res = await getDeptTree()
    deptOptions.value = res.data
  } catch (error) {
    console.error('获取部门树失败:', error)
    ElMessage.error('获取部门树失败')
  }
}

// 搜索按钮操作
const handleQuery = () => {
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

// 表单重置
const resetForm = () => {
  deptFormRef.value?.resetFields()
  Object.assign(form, {
    id: null,
    parentId: null,
    name: '',
    leader: '',
    phone: '',
    email: '',
    sort: 0,
    status: 1
  })
}

// 状态修改
const handleStatusChange = async (row) => {
  try {
    await updateDeptStatus(row.id, row.status)
    ElMessage.success(`修改部门状态成功`)
  } catch (error) {
    console.error('修改部门状态失败:', error)
    ElMessage.error('修改部门状态失败')
    row.status = row.status === 1 ? 0 : 1
  }
}

// 新增按钮操作
const handleAdd = (row) => {
  resetForm()
  dialog.title = '添加部门'
  dialog.visible = true
  if (row) {
    form.parentId = row.id
  }
}

// 修改按钮操作
const handleUpdate = async (row) => {
  resetForm()
  dialog.title = '修改部门'
  dialog.visible = true
  
  try {
    const res = await getDeptDetail(row.id)
    Object.assign(form, res.data)
  } catch (error) {
    console.error('获取部门详情失败:', error)
    ElMessage.error('获取部门详情失败')
  }
}

// 提交表单
const submitForm = () => {
  deptFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        if (form.id) {
          // 修改
          await updateDept(form.id, form)
          ElMessage.success('修改部门成功')
        } else {
          // 新增
          await createDept(form)
          ElMessage.success('新增部门成功')
        }
        dialog.visible = false
        getList()
        getDeptOptions()
      } catch (error) {
        console.error(form.id ? '修改部门失败:' : '新增部门失败:', error)
        ElMessage.error(form.id ? '修改部门失败' : '新增部门失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 删除按钮操作
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除部门"${row.name}"吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteDept(row.id)
      ElMessage.success('删除成功')
      getList()
      getDeptOptions()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

onMounted(() => {
  getList()
  getDeptOptions()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.mb-3 {
  margin-bottom: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 